package com.ruoyi.web.controller.ksdH5;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.utils.AliyunOssUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.HatchetMerchant;
import com.ruoyi.system.vo.StringUtilsss;

import net.sf.json.JSONObject;

public class Ksdh5Util {
	protected static final String PREFIX_MERCHANT_QUALIFICATION = "merchant_qualification";
	public static String md5Str(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}
	
	/**
     * 把json字符串转Map  
     * @param jsonStr
     * @return
     */
    public static Map<String, Object> getMap(String jsonStr){
    	 Map<String, Object> objmap = new HashMap<>();
    	 if ("{}".equals(jsonStr) || StringUtils.isEmpty(jsonStr)) {
    		 objmap.put("status", BusinessStatus.FAIL);
    		 objmap.put("msg", objmap.get("网络故障，请稍后再试"));
    		 return objmap;
		}
    	 JSONObject fromObject = JSONObject.fromObject(jsonStr);
    	 @SuppressWarnings("unchecked")
		Map<String, String> strMap = (Map<String,String>)fromObject;
    	 for (String key:strMap.keySet()) {
    		 objmap.put(key,strMap.get(key));
		}
    	 Map<String, Object> reMap = new HashMap<>();
    	 //token失效	
    	 if ("501".equals(objmap.get("apistatus").toString())) {
    		 reMap.put("status", "out");
    		 reMap.put("msg", objmap.get("error"));
    		 return reMap;								
		}
    	 //版本号不正确
	    if ("502".equals(objmap.get("apistatus").toString())) {
    		 reMap.put("status", BusinessStatus.FAIL);
    		 reMap.put("msg", objmap.get("error"));
    		 return reMap;								
		}
    	 //系统报错
    	 if ("500".equals(objmap.get("apistatus").toString())) {
    		 reMap.put("status", BusinessStatus.FAIL);
    		 reMap.put("msg", objmap.get("error"));
    		 								
		} else if ("200".equals(objmap.get("apistatus").toString())) {
			if (StringUtils.isNotEmpty(objmap.get("error").toString())) {
				 reMap.put("status", BusinessStatus.FAIL);
	    		 reMap.put("msg", objmap.get("error"));
			}else {
				reMap.put("status", BusinessStatus.SUCCESS);
	    		reMap.put("msg", objmap.get("apimsg"));
	    		reMap.put("obj", objmap);
			}
		}
    	 return reMap;
    }
 
    /**
     * 检测session是否过期
     * @param request
     * @param response
     * @return  没过期 true 过期false
     */
    public static boolean checkSession(HttpServletRequest request,HttpServletResponse response) {
    	HttpSession session = request.getSession();
    	Object merchant = session.getAttribute("merchant");
    	Object token = session.getAttribute("token");
    	//判断没有登陆状态
    	if (StringUtils.isNull(merchant)|| StringUtils.isNull(token)) {
    		return false;
    	} else {
			return true;
		}
	}
    
    /**
     * 检测是否实名
     * @param request
     * @param response
     * @return
     */
    public static boolean checkRealName(HttpServletRequest request,HttpServletResponse response) {
    	HttpSession session = request.getSession();
    	Object obj = session.getAttribute("merchant");
    	HatchetMerchant merchant =(HatchetMerchant) obj;
		//未实名认证
		if (StringUtils.isEmpty(merchant.getIdCardNumber())) {
			return false;
		}
    	else {
    		return true;
		}
    	
	}
	
    /**
     * 获得token方法
     * @param request
     * @param response
     * @return
     */
   public static String getToken(HttpServletRequest request,HttpServletResponse response) {
	   HttpSession session = request.getSession();
	   return  session.getAttribute("token").toString();
	  
   }
    
   /**
    * 获得当前登陆用户
    * @param request
    * @param response
    * @return
    */
  public static HatchetMerchant getMerchant(HttpServletRequest request,HttpServletResponse response) {
	   HttpSession session = request.getSession();
	   return  (HatchetMerchant)session.getAttribute("merchant");
	  
  }
    
    
    /**
	 * 上传身份证图片
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @param in
	 * @param imageType  10E是身份证正面  10F是反面
	 * @return
	 * @throws FileUploadException 
	 * @throws IOException 
	 */
	@PostMapping("/imgFile")
	public synchronized static Map<String, Object>  imgFile(String merchantNo,MultipartFile multipartFile,  String imageType,String ocrType) throws FileUploadException, IOException {
		Map<String, Object> results = new HashMap<>();
		InputStream in = null;
		in = multipartFile.getInputStream();
		//上传图片
		String uuid = StringUtilsss.randomUUID();
		String path = String.format("%s/%s/%s_%s.png", PREFIX_MERCHANT_QUALIFICATION,
				merchantNo, imageType, uuid);
		String path_url = AliyunOssUtil.upload(path, in);
		if (StringUtils.isEmpty(path_url)) {
			results.put("status", BusinessStatus.FAIL);
			results.put("msg", "上传失败");
			return results;
		}
		results.put("status", BusinessStatus.SUCCESS);
		results.put("msg", "上传成功");
		results.put("url", path_url);
		return results;
	}
}
